<template>
  <div class="dashboard-container">
    <!-- 日期选择器 -->
    <div class="date-picker">
      <el-date-picker
        v-model="selectedDate"
        type="date"
        placeholder="选择日期"
        format="yyyy-MM-dd"
        value-format="yyyy-MM-dd"
      />
      <el-button type="primary" icon="el-icon-search" @click="handleDateSearch">查看</el-button>
    </div>

    <!-- 统计卡片 -->
    <el-row :gutter="24" class="stat-row">
      <el-col :span="4" v-for="item in stats" :key="item.label">
        <div class="stat-card" :style="{ background: item.bgColor }">
          <div class="stat-icon" :style="{ color: item.iconColor }">
            <i :class="item.icon"></i>
          </div>
          <div class="stat-info">
            <div class="stat-number">{{ displayNumbers[item.label] }}</div>
            <div class="stat-label">{{ item.label }}</div>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 柱状图 + 分页 -->
    <el-card shadow="hover" class="chart-card">
      <div class="chart-header">
        <h3 class="chart-title">课程浏览量统计</h3>
      </div>
      <div class="bar-chart" ref="barChart"></div>
      <div class="chart-pagination">
        <el-button @click="prevPage" :disabled="currentPage === 1"> <</el-button>
        <span>第 {{ currentPage }} / {{ totalPages }} 页</span>
        <el-button @click="nextPage" :disabled="currentPage === totalPages"> ></el-button>
      </div>
    </el-card>
  </div>
</template>
<script>
import * as echarts from 'echarts'
import api from '@/api/edu/dashboard'

export default {
  name: 'Dashboard',
  data() {
    return {
      selectedDate: this.getToday(),
      stats: [],
      displayNumbers: {},
      barChart: null,
      barChartData: {
        categories: [],
        data: []
      },
      currentPage: 1,
      pageSize: 10
    }
  },
  computed: {
    totalPages() {
      return Math.ceil(this.barChartData.data.length / this.pageSize)
    },
    paginatedChartData() {
      const start = (this.currentPage - 1) * this.pageSize
      const end = start + this.pageSize
      return {
        categories: this.barChartData.categories.slice(start, end),
        data: this.barChartData.data.slice(start, end)
      }
    }
  },
  mounted() {
    this.loadData()
    this.initBarChart()
    window.addEventListener('resize', this.resizeHandler)
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.resizeHandler)
    this.barChart && this.barChart.dispose()
  },
  methods: {
    getToday() {
      const d = new Date()
      return `${d.getFullYear()}-${(d.getMonth() + 1)
        .toString()
        .padStart(2, '0')}-${d.getDate().toString().padStart(2, '0')}`
    },

    async loadData() {
      try {
        const res = await api.getDashboardData(this.selectedDate)
        if (res.code !== 20000) {
          this.$message.error('数据请求失败')
        }
        const summary = res.data
        const courseViewList = summary.courseViewCountVoList || []

        this.stats = [
          {
            label: '注册人数',
            value: summary.registerCount,
            icon: 'el-icon-user-solid',
            bgColor: 'rgba(107, 115, 255, 0.15)',
            iconColor: '#6B73FF'
          },
          {
            label: '登录人数',
            value: summary.loginCount,
            icon: 'el-icon-s-check',
            bgColor: 'rgba(255, 126, 95, 0.15)',
            iconColor: '#FF7E5F'
          },
          {
            label: '新增课程数',
            value: summary.courseAddCount,
            icon: 'el-icon-document-copy',
            bgColor: 'rgba(67, 206, 162, 0.15)',
            iconColor: '#43CEA2'
          },
          {
            label: '发布文章数',
            value: summary.articleCount,
            icon: 'el-icon-edit-outline',
            bgColor: 'rgba(247, 151, 30, 0.15)',
            iconColor: '#F7971E'
          },
          {
            label: '评论数',
            value: summary.commentCount,
            icon: 'el-icon-chat-line-round',
            bgColor: 'rgba(86, 204, 242, 0.15)',
            iconColor: '#56CCF2'
          },
          {
            label: '订单数',
            value: summary.orderCount,
            icon: 'el-icon-shopping-cart-full',
            bgColor: 'rgba(255, 106, 0, 0.15)',
            iconColor: '#FF6A00'
          }
        ]

        this.displayNumbers = this.stats.reduce((acc, cur) => {
          acc[cur.label] = 0
          return acc
        }, {})

        this.barChartData.categories = courseViewList.map(item => item.courseTitle)
        this.barChartData.data = courseViewList.map(item => item.courseViewCount)

        this.currentPage = 1
        this.animateNumbers()
        this.updateBarChart()
      } catch (error) {
        console.error('获取数据失败', error)
      }
    },

    animateNumbers() {
      this.stats.forEach(item => {
        let current = 0
        const step = Math.ceil(item.value / 60)
        const timer = setInterval(() => {
          current += step
          if (current >= item.value) {
            current = item.value
            clearInterval(timer)
          }
          this.$set(this.displayNumbers, item.label, current)
        }, 33)
      })
    },

    initBarChart() {
      this.barChart = echarts.init(this.$refs.barChart)
      this.updateBarChart()
    },

    updateBarChart() {
      const chartData = this.paginatedChartData
      const option = {
        color: ['#6B73FF'],
        tooltip: {
          trigger: 'axis',
          axisPointer: { type: 'shadow' }
        },
        grid: {
          left: 20,
          right: 20,
          bottom: 30,
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: chartData.categories,
          axisLabel: {
            interval: 0,
            formatter: value => (value.length > 8 ? value.slice(0, 8) + '...' : value)
          }
        },
        yAxis: {
          type: 'value',
          splitLine: { lineStyle: { type: 'dashed', color: '#eee' } }
        },
        series: [
          {
            name: '课程浏览量',
            type: 'bar',
            data: chartData.data,
            barWidth: 60,
            itemStyle: {
              borderRadius: [6, 6, 0, 0],
              color: {
                type: 'linear',
                x: 0, y: 0, x2: 0, y2: 1,
                colorStops: [
                  { offset: 0, color: '#83a6ed' },
                  { offset: 1, color: '#6B73FF' }
                ]
              }
            },
            emphasis: {
              itemStyle: {
                color: {
                  type: 'linear',
                  x: 0, y: 0, x2: 0, y2: 1,
                  colorStops: [
                    { offset: 0, color: '#a6c1ee' },
                    { offset: 1, color: '#8B93FF' }
                  ]
                }
              }
            },
            animationDuration: 1000,
            animationEasing: 'elasticOut'
          }
        ]
      }

      this.barChart.setOption(option)
    },

    handleDateSearch() {
      this.loadData()
    },

    resizeHandler() {
      this.barChart && this.barChart.resize()
    },

    prevPage() {
      if (this.currentPage > 1) {
        this.currentPage--
        this.updateBarChart()
      }
    },

    nextPage() {
      if (this.currentPage < this.totalPages) {
        this.currentPage++
        this.updateBarChart()
      }
    }
  }
}
</script>
<style>
.dashboard-container {
  padding: 32px 40px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.date-picker {
  margin-bottom: 24px;
}

.stat-row {
  margin-top: 25px;
  margin-bottom: 32px;
}

.stat-card {
  padding: 20px 24px;
  border-radius: 20px;
  color: #333;
  display: flex;
  align-items: center;
  background: #fff;
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.07);
  transition: all 0.3s;
}

.stat-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 18px 35px rgba(0, 0, 0, 0.12);
}

.stat-icon {
  font-size: 36px;
  width: 60px;
  text-align: center;
}

.stat-info {
  flex: 1;
}

.stat-number {
  font-size: 30px;
  font-weight: bold;
}

.stat-label {
  font-size: 14px;
  color: #666;
  margin-top: 4px;
}

.chart-card {
  padding: 24px 30px;
  border-radius: 20px;
  background: #fff;
  box-shadow: 0 12px 38px rgba(0, 0, 0, 0.07);
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.chart-title {
  font-size: 20px;
  font-weight: bold;
}

.bar-chart {
  height: 360px;
}

.chart-pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 60px;
  gap: 20px;
}
</style>
